#!/bin/bash
#The plotter is called from any CARBLogger driver
#It depends upon the installation of gnuplot and gnuplotfeed
while read line; do
eval $line
done < Config/config
cleanup()
{
    echo "Caught Signal ... cleaning up."
    if !(rm -f Data/.locked > /dev/null); then
        {
                  exit 1
        }
    fi
    kill -9 ${feed_id}
    echo "Done cleanup ... quitting."
     exit 0
}

########################################################
#	GET THE PATH TO THE CURRENT DRIVER THE PARAMETERS TO PLOT                   #
########################################################
#DIR returns operating directory of the testd script

DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

#########################################################
#	CHECK THE EXISTANCE OF NEEDED RESOURCES				#
#	MJV													#
#########################################################
if !( which feedgnuplot ); then
	echo "No feedgnuplot has been found here"
	echo "exiting"
	exit 1
elif !(which gnuplot); then
 	echo "No gnuplot has been found here"
	echo "exiting"
	exit 1
elif !( which pgrep ); then
	echo "No pgrep...stopping"
	exit 1	
fi
####################################################################################
#	SYNCHRONIZE 60 Sec PLOTTING CYCLE WITH FRONT DISPLAY ~ 5 sec after the top of the minute
#####################################################################################
while [ `date "+%S"` != 25 ]
do
	sleep .1
done


######################################################################
#	GRAB ALL OF THE DISPLAY PARAMETERS AND PLOT THEM
######################################################################
#TRAP CTRL+C
catchup="0"
trap cleanup 1 2 3 6 15
while [ : ]; do
	if [ $catchup -eq 0 ]; then
		echo "clear"
		hour=`date '+%H'`
		minute=`date '+%M'`
		for h in `seq -w 0 $hour`
		do
			(grep "_${h}:" | grep 'ECO_1=' | sed 's/--[A-Z]*--//' | sed 's/:::/ /g' | sed 's/_/ /g'| awk '{ print $2" "$4","$6","$9","$12 }' | sed 's/1=//g')<Data/${saroad}-`date '+%Y'`-`date '+%d'`-`date '+%m'`
			catchup="1"
		done
		catchup=1
	fi
	data=$(tail -n 1000 Data/${saroad}-`date '+%Y'`-`date '+%d'`-`date '+%m'`| grep `date '+_%H:'` | grep 'BAM1=')  
	for i in 'PM10s_1=' ; 
	do
		if [ `date '+%H:%M'` == "01:00" ]; then
			echo clear
			sleep 60
		else
						
			hour=`date '+%H'`
			minute=`date '+%M'`
			echo ${data} | grep "_${hour}:" | grep 'ECO_1=' | sed 's/--[A-Z]*--//' | sed 's/:::/ /g' | sed 's/_/ /g'| awk '{ print $2" "$4","$6","$9","$12 }' | sed 's/1=//g' 
			sleep 60
		fi
	done

done | feedgnuplot --domain --timefmt '%H:%M' --stream --curvestyleall 'with linespoints' --binwidth '600' --xlabel 'Time [HH:MM]' --ylabel 'ng/m3' --y2label 'lpm' --y2 2 --y2 3 --legend 0 "ECO" --legend 1 "OCO" --legend 2 "SAM FLOW" --legend 3 "TOT FLOW" --title "BC1050"
